package com.demo.config.security;

import com.demo.common.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;


/**
 * 框架异常处理
 * @date 2021/4/30
 */
@Configuration
public class CustomExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, Exception e) {
        e.printStackTrace();
        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
        //从上往下配置
        JsonResult<String> fail = JsonResult.fail("系统错误");
        ;

        if (e instanceof AuthenticationCredentialsNotFoundException) {
            fail = JsonResult.fail("请去登入");
        } else if (e instanceof AccessDeniedException) {
            fail = JsonResult.fail("无权限访问");
        } else if (e instanceof RuntimeException) {
            fail = JsonResult.fail(e.getMessage());
        }


        HashMap<String, ?> hashMap = new ObjectMapper().convertValue(fail, HashMap.class);
        mv.addAllObjects(hashMap);
        return mv;
    }
}
